package com.freeman.cement.exception;

import com.freeman.cement.entity.ResponseResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 66
 * 创建全局统一异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public <T> ResponseResult<T> exceptionHandler(Exception e) {
        //这里先判断拦截到的Exception是不是我们自定义的异常类型
        if (e instanceof AppException) {
            AppException appException = (AppException) e;
            return ResponseResult.error(appException.getCode(), appException.getMsg());
        }
        //如果拦截的异常不是我们自定义的异常(例如：数据库主键冲突)
        //return ResponseResult.error(500, "服务端处理异常");
        //return ResponseResult.error(500, "服务端处理异常:" + e.toString());

        logger.error("处理异常:", e);
        //logger.error("处理异常:" + e.getMessage());
        return ResponseResult.error(500, "服务端处理异常:" + e.getMessage());
    }

}